<?php

/**
 * This is the model class for table "category".
 *
 * The followings are the available columns in table 'category':
 * @property string $id
 * @property string $lft
 * @property string $rgt
 * @property integer $level
 * @property string $name
 * @property string $description
 */
class Category extends CActiveRecord {

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'category';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name,orders', 'required','message' => 'trường này không được bỏ trống'),
            array('level,orders', 'numerical', 'integerOnly' => true,'message' => 'chỉ được nhập số'),
            array('lft, rgt', 'length', 'max' => 10),
            array('name', 'length', 'max' => 255),
            array('description', 'safe'),
            array('parents,seo_title,seo_keywork,seo_description', 'safe'),
            array('image', 'file', 'types'=>'jpg, gif, png','allowEmpty'=>true,'message' => 'bạn chỉ được upload file hình png,jpg hoặc gif'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, lft, rgt, level, name, description', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'lft' => 'Lft',
            'rgt' => 'Rgt',
            'level' => 'Level',
            'name' => 'Tên danh mục',
            'description' => 'Mô tả',
            'parents' => 'Danh mục cha',
            'orders' => 'thứ tự'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('lft', $this->lft, true);
        $criteria->compare('rgt', $this->rgt, true);
        $criteria->compare('level', $this->level);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('description', $this->description, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Category the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    

    /**
     * add behaviors
     * @return type 
     */
    public function behaviors() {
        return array(
            'nestedSetBehavior' => array(
                'class' => 'NestedSetBehavior',
                'leftAttribute' => 'lft',
                'rightAttribute' => 'rgt',
                'levelAttribute' => 'level',
            ),
        );
    }
    
    /**
     *
     * @param type $id 
     */
    public static function getDetailCategory($id){
        $category = self::model()->findByPk($id);
    }
    
    /**
     * get list category
     */
    public static function getListCategory($parent,$stop = null){
        $result = array();
        self::loopNode($result, $parent, $stop,"");
        return $result;
    }
    
    /**
     * 
     */
    public static function getListCategoryWithoutRoot($parent,$stop = null){
        $listCategory = self::getListCategory($parent,$stop);
        foreach($listCategory as $key => $item){
            //$listCategory[$key] = trim($listCategory[$key],"--");
            if($key == 1){
                unset($listCategory[$key]);
            }
        }
        return $listCategory;
    }
    
    /**
     *
     * @param type $result
     * @param type $parent
     * @param type $stop
     * @return type 
     */
    public static function loopNode(&$result,$parent,$stop,$prefix,$separ = " - -"){
        if($stop != null && $parent == $stop)
            return true;
        else{
            $category = self::model()->findByPk($parent);
            $result[$category->id] = $prefix." ".$category->name;
            foreach($category->children()->findAll() as $item){
                self::loopNode($result, $item->id, $stop,$prefix.$separ,$separ);
            }
        }
    }
    
    /**
     * get image of category
     */
    public function getImage(){
        $default = "default.gif";
        if($this->image != null && !is_object($this->image) && file_exists(PATH_IMAGE_CATEGORY.$this->image)){
            return $this->image;
        }else{
            if(!is_object($this->image) && $this->image != null && !file_exists(PATH_IMAGE_CATEGORY.$this->image)){
                return $default;
            }
        }
        return false;
    }
    
    /**
     * 
     */
    public function getArrayIdChildrenCategory(){
        $return = array($this->id);
        $children = $this->descendants()->findAll(array('order'=>'orders ASC'));
        foreach($children as $item){
            $return[] = $item->id;
        }
        return $return;
    }
    
    /**
     * 
     */
    public function getAllProduct($sort = 'view DESC',$offset = 0,$limit = LIMIT){
        $criteria = new CDbCriteria();
        $criteria->join='INNER JOIN category_product ON category_product.product_id = t.product_id';
        $criteria->addInCondition("category_product.category_id",$this->getArrayIdChildrenCategory());
        $criteria->addCondition('`status` = 1');
        $criteria->order = $sort;
        $criteria->group = "t.product_id";
        $criteria->offset = $offset;
        $criteria->limit = $limit;
        $products = Product::model()->findAll($criteria);
        return $products;
    }
    
    /**
     * 
     */
    public function getUrl(){
        return Yii::app()->createUrl('category/index',array('title' => getTitleUrl($this->name),'id' => $this->id));
    }
    
    /**
     * 
     */
    public function registerMeta(){
       $keyword = $this->seo_keywork != null?$this->seo_keywork:$this->name;
       $description = $this->seo_description != null?$this->seo_description:$this->name;
       Yii::app()->clientScript->registerMetaTag($keyword,'keywords');
       Yii::app()->clientScript->registerMetaTag($description,'description');
    }
    
    /**
     * 
     */
    public function getSeoTitle(){
        if($this->seo_title == null){
            return $this->name;
        }
        return $this->seo_title;
    }
    
    
    /**
     * 
     */
    public function randomProduct($limit = 12){
        $count = Product::model()->countByAttributes(array('category_id'=>$this->id));
        if($count > $limit){
            $offset = rand(0,$count - $limit);
        }
        $offset = 0;
        $criteria = new CDbCriteria();
        $criteria->addCondition('category_id = :category_id');
        $criteria->params = array(':category_id' => $this->id);
        $criteria->limit = $limit;
        $criteria->offset = $offset;
        return Product::model()->findAll($criteria);
    }

}
